<template>
  <div class="form-content">
    <div class="title">
      筛选条件
    </div>

    <el-form class="content">
      <template v-for="(item, index) in list">
        <el-form-item :key="index">
          <el-row>
            <el-col :span="8">
              <el-select
                v-model="item.fieldName"
                placeholder="请选择要筛选的字段名"
                @change="fieldChange(item)">
                <el-option
                  v-for="item in fieldList"
                  :key="item.fieldName"
                  :label="item.name"
                  :value="item.fieldName"/>
              </el-select>
            </el-col>

            <el-col v-if="showCondition(item.formType)" :span="1">&nbsp;</el-col>

            <el-col
              v-if="showCondition(item.formType)"
              :span="4">
              <el-select
                v-model="item.condition"
                placeholder="请选择范围"
                @change="conditionChange(item)">
                <el-option
                  v-for="option in getConditionOptions(item.formType)"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"/>
              </el-select>
            </el-col>

            <el-col :span="1">&nbsp;</el-col>

            <el-col :span="['datetime', 'date', 'map_address'].includes(item.formType) ? 13 : 8">
              <el-select
                v-if="['checkbox', 'select', 'state_cause', 'checkStatus', 'dealStatus'].includes(item.formType)"
                v-model="item.value"
                multiple
                placeholder="请选择筛选条件">
                <el-option
                  v-for="(option, o_index) in item.setting"
                  :key="o_index"
                  :label="option.hasOwnProperty('label') ? option.label : option"
                  :value="option.hasOwnProperty('value') ? option.value : option"/>
              </el-select>

              <el-select
                v-else-if="['checkStatus', 'dealStatus'].includes(item.formType)"
                v-model="item.value"
                placeholder="请选择筛选条件">
                <el-option
                  v-for="option in item.setting"
                  :key="option"
                  :label="option"
                  :value="option"/>
              </el-select>

              <el-date-picker
                v-else-if="['date', 'datetime'].includes(item.formType)"
                v-model="item.value"
                :value-format="item.formType === 'date' ? 'yyyy-MM-dd' : 'yyyy-MM-dd HH:mm:ss'"
                :type="item.formType === 'date' ? 'daterange' : 'datetimerange'"
                style="padding: 0px 10px;"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"/>

              <wk-user-select
                v-else-if="item.formType === 'user'"
                v-model="item.value"
                :request="item.config.request"
                :params="item.config.params"
                radio
                style="width: 100%;"
                @change="handleArrayChange(item, arguments[1])" />

              <wk-dep-select
                v-else-if="item.formType === 'structure'"
                v-model="item.value"
                :request="item.config.request"
                :props="item.config.props"
                radio
                style="width: 100%;"
                @change="handleArrayChange(item, arguments[1])" />

              <wk-product-category
                v-else-if="item.formType === 'category'"
                :type="item.config.type"
                v-model="item.value"
                @change="handleCategoryChange(item, arguments[0])" />

              <v-distpicker
                v-else-if="item.formType === 'map_address'"
                :province="item.value.state"
                :city="item.value.city"
                :area="item.value.area"
                @province="handleAddressChange($event, item, 'state')"
                @city="handleAddressChange($event, item, 'city')"
                @area="handleAddressChange($event, item, 'area')"/>

              <el-input
                v-else
                v-model="item.value"
                placeholder="请输入筛选条件" />
            </el-col>

            <el-col
              :span="1"
              class="delete">
              <i
                class="el-icon-error delete-btn"
                @click="handleDelete(index)"/>
            </el-col>
          </el-row>
        </el-form-item>
      </template>
    </el-form>

    <div
      v-if="showErrors"
      class="error-msg el-icon-warning">
      <span class="desc">筛选条件中有重复项！</span>
    </div>

    <el-button
      type="text"
      @click="handleAdd">
      + 添加筛选条件
    </el-button>
  </div>
</template>

<script>
/**
 * Created by yxk at 2020/6/5
 */
import { userListAPI } from '@/api/common'
import { depListAPI } from '@/api/common'

import WkUserSelect from '@/components/NewCom/WkUserSelect/index'
import WkDepSelect from '@/components/NewCom/WkDepSelect/index'
import WkProductCategory from '@/components/NewCom/WkProductCategory'

import { objDeepCopy } from '@/utils'
import { isEmpty } from '@/utils/types'
import { isArray } from '../../../../utils/types'

export default {
  name: 'FormContent',
  components: {
    WkUserSelect,
    WkDepSelect,
    WkProductCategory
  },
  props: {
    id: {
      type: [String, Number],
      default: null
    },
    defaultValue: {
      type: Array,
      default: () => []
    },
    fieldList: {
      type: Array,
      required: true,
      default: () => {
        return []
      }
    },

    // 产品类型树请求配置
    categoryConfig: {
      type: Object,
      default: () => {
        return {
          type: 'jxc'
        }
      }
    },
    // 用户列表请求配置
    userConfig: {
      type: Object,
      default: () => {
        return {
          request: userListAPI,
          params: { pageType: 0 }
        }
      }
    },
    // 部门请求配置
    deptConfig: {
      type: Object,
      default: () => {
        return {
          request: depListAPI,
          props: {
            value: 'deptId',
            label: 'name'
          }
        }
      }
    }
  },
  data() {
    return {
      showErrors: false,
      list: [],

      conditionMap: {
        is: { label: '等于', value: 'is', type: 1 },
        in: { label: '等于', value: 'in', type: 13 },
        isNot: { label: '不等于', value: 'isNot', type: 2 },
        contains: { label: '包含', value: 'contains', type: 3 },
        notContains: { label: '不包含', value: 'notContains', type: 4 },
        startWith: { label: '开始于', value: 'startWith', type: null },
        endWith: { label: '结束于', value: 'endWith', type: null },
        isNull: { label: '为空', value: 'isNull', type: '' },
        isNotNull: { label: '不为空', value: 'isNotNull', type: 6 },
        gt: { label: '大于', value: 'gt', type: 7 },
        egt: { label: '大于等于', value: 'egt', type: 8 },
        lt: { label: '小于', value: 'lt', type: 9 },
        elt: { label: '小于等于', value: 'elt', type: 10 },
        datetime: { label: '日期时间', value: 'datetime', type: 12 },
        date: { label: '日期', value: 'date', type: 11 },
        checkbox_in: { label: '等于', value: 'checkbox_in', type: 15 },
        checkbox_not: { label: '不等于', value: 'checkbox_not', type: 16 }
      }
    }
  },
  watch: {
    fieldList: {
      handler(val) {
        if (this.defaultValue.length === 0) {
          this.list = []
          this.handleAdd()
        }
      },
      deep: true,
      immediate: true
    },
    defaultValue: {
      handler(val) {
        if (val.length > 0) {
          if (this.id) {
            this.setDefault(val)
          } else {
            this.list = objDeepCopy(val)
            this.list.forEach(item => {
              this.conditionChange(item)
            })
          }
        } else {
          this.list = []
          this.handleAdd()
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    handleAdd() {
      this.list.push({
        fieldName: '', // 字段
        name: '', // 字段名
        formType: '', // 字段类型
        condition: 'contains', // 条件
        conditionVal: '', // 条件value
        config: null, // 特殊配置
        value: '' // 筛选值
      })
    },

    handleDelete(index) {
      this.$confirm('您确定要删除这一条数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.list.splice(index, 1)
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    /**
     * 条件数据源
     */
    getConditionOptions(formType = '') {
      let arr = []

      if ([
        'user',
        'checkStatus',
        'dealStatus',
        'structure'
      ].includes(formType)) {
        arr = ['is', 'isNot']
      } else if (['select', 'state_cause'].includes(formType)) {
        arr = ['in', 'isNot']
      } else if (formType === 'checkbox') {
        arr = ['checkbox_in', 'checkbox_not']
      } else if (formType === 'date') {
        arr = ['date']
      } else if (formType === 'datetime') {
        arr = ['datetime']
      } else if ([
        'text',
        'textarea',
        'module'
      ].includes(formType)) {
        arr = ['is', 'isNot', 'contains', 'notContains']
      } else if ([
        'floatnumber',
        'number'
      ].includes(formType)) {
        arr = ['is', 'isNot', 'contains', 'notContains', 'isNull', 'isNotNull', 'gt', 'egt', 'lt', 'elt']
      } else if (formType === 'category') {
        arr = ['is', 'isNot', 'contains', 'notContains']
      } else if ([
        'supplier_cause',
        'purchase_cause',
        'sale_cause',
        'warehouse_cause',
        'related_id',
        'collection_object',
        'customer'
      ].includes(formType)) {
        arr = ['is', 'isNot', 'contains', 'notContains']
      } else {
        arr = ['is', 'isNot', 'contains', 'notContains', 'startWith', 'endWith', 'isNull', 'isNotNull', 'gt',
          'egt', 'lt', 'elt']
      }

      const res = []
      arr.forEach(o => {
        if (this.conditionMap[o]) {
          res.push(this.conditionMap[o])
        }
      })
      return res
    },

    /**
     * 是否展示条件
     */
    showCondition(formType) {
      return ![
        'date',
        'datetime',
        'business_type',
        'category',
        'map_address'
      ].includes(formType)
    },

    setDefault(list) {
      const keys = Object.keys(this.conditionMap)

      list.forEach(item => {
        const findRes = this.fieldList.find(o => o.fieldName === item.name)
        if (findRes) {
          const tmp = {
            fieldName: findRes.fieldName,
            name: findRes.name,
            formType: findRes.formType
          }

          if (tmp.formType === 'map_address') {
            tmp.value = {
              state: '',
              city: '',
              area: ''
            }
          } else if (['select', 'checkbox', 'state_cause'].includes(tmp.formType)) {
            tmp.setting = findRes.setting || []
            tmp.value = item.values
          } else if (['date', 'datetime', 'user', 'category'].includes(tmp.formType)) {
            tmp.value = item.values
          } else {
            tmp.value = isArray(item.values) ? (item.values[0] || '') : ''
          }

          if (tmp.formType === 'user') {
            tmp.config = this.userConfig
          } else if (tmp.formType === 'structure') {
            tmp.config = this.deptConfig
          } else if (tmp.formType === 'category') {
            tmp.config = this.categoryConfig
          }

          tmp.conditionVal = item.type
          tmp.condition = keys.find(key => this.conditionMap[key].type == item.type) || 'contains'
          this.list.push(tmp)
        }
      })
    },

    fieldChange(field, defaultVal = null) {
      console.log('change: ', field)

      const findRes = this.fieldList.find(o => o.fieldName === field.fieldName)
      if (findRes) {
        field.formType = findRes.formType
        field.name = findRes.name

        if (field.formType === 'map_address') {
          field.value = {
            state: '',
            city: '',
            area: ''
          }
        } else if (['select', 'checkbox', 'state_cause'].includes(field.formType)) {
          field.setting = findRes.setting || []
          field.value = []
        } else if (['date', 'datetime', 'user', 'category', 'structure'].includes(field.formType)) {
          field.value = []
        } else {
          field.value = ''
        }

        if (field.formType === 'user') {
          field.config = this.userConfig
        } else if (field.formType === 'structure') {
          field.config = this.deptConfig
        } else if (field.formType === 'category') {
          field.config = this.categoryConfig
        }

        // 条件校准
        console.log('field', field)
        const arr = this.getConditionOptions(field.formType)
        console.log('arr', arr)
        if (arr.length > 0) {
          const findRes = arr.find(o => o.value === 'contains')
          if (!findRes) {
            field.condition = arr[0].value
            field.conditionVal = arr[0].type
          } else {
            field.condition = 'contains'
            field.conditionVal = 3
          }
        } else {
          field.condition = 'contains'
          field.conditionVal = 3
        }
      }
      // this.conditionChange(field)

      const arr = this.list.filter(item => {
        return item.fieldName === field.fieldName
      })
      this.showErrors = arr.length > 1
      console.log('list filter: ', this.list)
    },

    conditionChange(field) {
      field.conditionVal = this.conditionMap[field.condition].type || ''
    },

    handleArrayChange(field, arr = []) {
      field.arr = arr
    },

    handleCategoryChange(item, data) {
      // console.log('dddddddddddddddd', data)
      item.valueContent = data.valueContent
      this.$set(item, 'valueContent', data.valueContent)
      // data => item.valueContent = data.valueContent
    },

    /**
     * 修改位置
     */
    handleAddressChange(data, item, field) {
      item.value[field] = data.value
    },

    getValue() {
      if (this.showErrors) {
        this.$message.error('筛选条件中有重复项！')
        return null
      }
      for (let i = 0; i < this.list.length; i++) {
        const o = this.list[i]
        if (!o.fieldName || o.fieldName === '') {
          this.$message.error('筛选的字段名称不能为空！')
          return null
        } else if (o.formType == 'map_address') {
          if (!o.value.state && !o.value.city && !o.value.area) {
            this.$message.error('筛选内容不能为空！')
            return null
          }
        }
        if (isEmpty(o.value)) {
          this.$message.error('筛选内容不能为空！')
          return null
        }
      }
      return this.list
    }
  }
}
</script>

<style scoped lang="scss">
.form-content {
  .title {
    margin-bottom: 10px;
  }

  .el-form {
    max-height: 300px;
    overflow-y: auto;

    .el-form-item {
      margin-bottom: 0;
      .el-row {
        margin-bottom: 20px;
        .delete-btn {
          margin-left: 15px;
          color: #bbb;
          cursor: pointer;
        }
        .el-select,
        .el-date-editor {
          width: 100%;
        }
      }
    }
  }

  .error-msg {
    width: 100%;
    font-size: 14px;
    color: #f56c6c;
    margin-top: 10px;
    .desc {
      padding-left: 8px;
    }
  }
}
</style>
